<?php

// +----------------------------------------------------------------------
// |  授权信息
// +----------------------------------------------------------------------
namespace app\admin\actions;
use think\facade\Session;
use think\facade\Db;

error_reporting(0);

class Action
{
	
	protected $userinfo = [];				//用户信息
	protected $userAction = null;			//用户权限缓存
	protected $isAdmin = false;			//是否管理员
    protected static $instance = null;  	//实列对象
	
	public function __construct($userInfo = null) {
		$this->userinfo = $userInfo ?: request()->userInfo;
		$this->isAdmin = $this->userinfo['is_admin'] == 1 ? true : false;
    }
	
    /**
     * 获取示例
     * @param array $options 实例配置
     * @return static
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new self($options);
        }
        return self::$instance;
    }

    /**
     * 验证授权
	 * @param string $function  
	 * @param string $action_code  
     * @return  boole
     */
    public function check($function='-1',$actionCode='00')
    {
    	$falg = $this->isAdmin;
    	$userAction = $this->getAuthList();
		foreach( explode(',',$actionCode) as $code ){
			if( in_array( $code , explode(',', $userAction[$function] ?? '' ) ) ){
				$falg = true;
			}
		}
		if($this->isAdmin){ return true; }
		return $falg == false ? false : $userAction;
    }
	
	
	/**
     * 验证按钮授权-grid控件-form控件
	 * @param string $function  
	 * @param array $btns  
     * @return  array
     */
    public function checkBtnQuth($function,$btns=[],$field='btns')
    {
		$btn = [];
		if(isset($btns)){
			foreach($btns as  $v){
				$flag = false;
				if( isset($v[$field])  && count($v[$field]) > 0){
					$bs = [];
					$flag = true;
					foreach($v[$field] as  $k){
						if( !$k['action'] || $this->check( $function , $k['action'] ) ){
							array_push($bs,$k);
						}
					}
					$v[$field]	= $bs;
				}
				if(!$flag || count($v[$field]) > 0 ){
					if( !$v['action'] || $this->check( $function , $v['action'] ) ){
						array_push($btn,$v);
					}
				}
			}
		}
		return $btn;
    }
	
	//当前用户的授权信息
    public function getAuthList() {
		$org_id = $this->userinfo['org_id'];
		$result = [];
		if( $this -> userAction !== null ){
			$result = $this ->userAction;
		}else{
			$this -> userAction = $result = Db::table('xw_system_group') ->where('org_id',$org_id)->value('action');
		}
		if( !empty($result) ){
			$result = json_decode($result,true);
		}
		return $result;
    }
	

}
